<!DOCTYPE html>
<html lang="en">

<head>
	<title>three.js 战场</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
	<!-- <link type="text/css" rel="stylesheet" href="main.css"> -->
	<link rel="icon" href="/src/assets/k.ico">
	<style>
		* {
			margin: 0;
			padding: 0;
		}

		body {
			background-color: #fff;
			color: #444;
		}

		a {
			color: #08f;
		}
	</style>
</head>

<body>
	<div id="info">
	</div>

	<!-- Import maps polyfill -->
	<!-- Remove this when import maps will be widely supported -->

	<script type="importmap">
			{
				"imports": {
                    "three": "../../node_modules/three/build/three.module.js"
                }
			}
		</script>


	<script type="module">

		import * as THREE from 'three';
		// import Stats from './jsm/libs/stats.module.js';

		import { OrbitControls } from '../../node_modules/three/examples/jsm/controls/OrbitControls.js'
		import { OBJLoader } from '../../node_modules/three/examples/jsm/loaders/OBJLoader.js'
		import { MTLLoader } from '../../node_modules/three/examples/jsm/loaders/MTLLoader.js'
		// import { MD2CharacterComplex } from './jsm/misc/MD2CharacterComplex.js';
		// import { Gyroscope } from './jsm/misc/Gyroscope.js';
		let SCREEN_WIDTH = window.innerWidth;
		let SCREEN_HEIGHT = window.innerHeight;
		let objects = [];
		let isShiftDown = false;

		let container, stats;
		var camera, scene, renderer, meshBox2, meshBox, ground;
		let pointer = new THREE.Vector2();//创建二维平面
		const characters = [];
		window.scale = 2.0;
		let nCharacters = 0;
		let rollOverMaterial, rollOverMesh;
		let raycaster = new THREE.Raycaster();//创建光线投射对象
		let cameraControls;

		const controls = {

			moveForward: false,
			moveBackward: false,
			moveLeft: false,
			moveRight: false

		};

		const clock = new THREE.Clock();

		init();
		animate();

		function init() {
			container = document.createElement('div');
			document.body.appendChild(container);
			// CAMERA
			camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 4000);
			camera.position.set(500, 800, 1300);
			camera.lookAt(0, 0, 0);
			// SCENE
			scene = new THREE.Scene();
			scene.background = new THREE.Color(0xffffff);
			scene.fog = new THREE.Fog(0xffffff, 1000, 4000);
			scene.add(camera);

			const xxx = new THREE.BoxGeometry(50, 50, 50);
			const mtl = new THREE.MeshBasicMaterial({ color: 0xff00 });
			meshBox = new THREE.Mesh(xxx, mtl);
			meshBox.name = 'PAO';

			const rollOverGeo = new THREE.BoxGeometry(50, 50, 50);
			rollOverMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, opacity: 0.5, transparent: true });
			rollOverMesh = new THREE.Mesh(rollOverGeo, rollOverMaterial);
			scene.add(rollOverMesh);


			// 引入SCAR
			// const manager = new THREE.LoadingManager( loadModel );
			const loader = new OBJLoader();
			loader.load('../../../src/obj/scar/22.obj', function (obj) {
				scene.add(obj);
				objects.push(obj);
			});


			new MTLLoader()
				.load('../../../src/obj/scar/SCAR-20.mtl', function (materials) {
					materials.preload();
					new OBJLoader()
						.setMaterials(materials)
						.load('../../../src/obj/scar/SCAR-20.obj', function (obj) {
							obj.position.y = 200;
							obj.scale.x = (10, 10, 10);
							obj.scale.y = (10, 10, 10);
							obj.scale.z = (10, 10, 10);
							scene.add(obj);
						});
				});

			// const loader = new ObjectLoader();
			// // console.log(https://threejs.org/examples/models/obj/male02/male02.obj);
			// var xhr = new XMLHttpRequest();
			// xhr.open('get', 'https://threejs.org/examples/models/obj/male02/male02.obj', true);
			// // xhr.responseType = 'blob';
			// xhr.onload = (val) => {
			// 	console.log('xxxx')
			// 	console.log(typeof val.target.response);
			// 	const modelUrl = val.target.response;
			// 	// console.log(modelUrl)
			// 	object = loader.parse(modelUrl);
			// 	// console.log(modelUrl);
			// 	scene.add(object);
			// 	// loader.load(
			// 	// 	'../../../src/obj/scar/male02.obj',
			// 	// 	function (object) {
			// 	// 		console.log('object', object)
			// 	// 		scene.add(object);
			// 	// 	},
			// 	// 	function (xhr) {
			// 	// 		console.log((xhr.loaded / xhr.total * 100) + '% loaded');
			// 	// 	},
			// 	// 	function (error) {
			// 	// 		console.log('An error happened', error);
			// 	// 	}
			// 	// );
			// };
			// xhr.send();

			// LIGHTS
			scene.add(new THREE.AmbientLight(0x222222));
			const light = new THREE.DirectionalLight(0xffffff, 2.25);
			light.position.set(200, 450, 500);
			light.castShadow = true;
			light.shadow.mapSize.width = 1024;
			light.shadow.mapSize.height = 512;
			light.shadow.camera.near = 100;
			light.shadow.camera.far = 1200;
			light.shadow.camera.left = - 1000;
			light.shadow.camera.right = 1000;
			light.shadow.camera.top = 350;
			light.shadow.camera.bottom = - 350;
			scene.add(light);
			//  GROUND

			const axesHelper = new THREE.AxesHelper(10000);
			scene.add(axesHelper);

			const size = 10000;
			const divisions = 200;

			const gridHelper = new THREE.GridHelper(size, divisions, 0xff4400, 0x000000);
			scene.add(gridHelper);

			const gt = new THREE.TextureLoader().load('../assets/grasslight-big.jpg');
			const gg = new THREE.PlaneGeometry(10000, 10000);
			const gm = new THREE.MeshPhongMaterial({ color: 0xffffff, map: gt });

			ground = new THREE.Mesh(gg, gm);
			ground.rotation.x = - Math.PI / 2;
			ground.material.map.repeat.set(64, 64);
			ground.material.map.wrapS = THREE.RepeatWrapping;
			ground.material.map.wrapT = THREE.RepeatWrapping;
			ground.material.map.encoding = THREE.sRGBEncoding;
			// note that because the ground does not cast a shadow, .castShadow is left false
			ground.receiveShadow = true;
			objects.push(ground);
			scene.add(ground);
			// RENDERER
			renderer = new THREE.WebGLRenderer({ antialias: true });
			renderer.setPixelRatio(window.devicePixelRatio);
			renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
			container.appendChild(renderer.domElement);
			// renderer.outputEncoding = THREE.sRGBEncoding;
			// renderer.shadowMap.enabled = true;
			// renderer.shadowMap.type = THREE.PCFSoftShadowMap;
			document.addEventListener('resize', onWindowResize);
			document.addEventListener('pointermove', onPointerMove);
			document.addEventListener('pointerdown', onPointerDown);
			document.addEventListener('keydown', onDocumentKeyDown);
			document.addEventListener('keyup', onDocumentKeyUp);
			cameraControls = new OrbitControls(camera, renderer.domElement);
			cameraControls.enableRotate = true;
			// 限制旋转最大角度
			cameraControls.maxPolarAngle = 4 / Math.PI;
			// cameraControls.minPolarAngle = 4 / Math.PI;
			cameraControls.target.set(0, 50, 0);
			cameraControls.update();
		}

		function onPointerMove(e) {
			// pointer.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
			pointer.set((e.clientX / renderer.domElement.clientWidth) * 2 - 1, -(e.clientY / renderer.domElement.clientHeight) * 2 + 1);
			let intersectsObjArr = getSelsectOBj(raycaster, e);//通过封装的getSelsectOBj函数获取鼠标选中对象集合，e是点击事件对象
			if (intersectsObjArr) {
				rollOverMesh.position.copy(intersectsObjArr.point).add(intersectsObjArr.face.normal);
				rollOverMesh.position.divideScalar(50).floor().multiplyScalar(50).addScalar(25);
				render();
			}
		}
		function onPointerDown(e) {
			pointer.set(e.clientX / renderer.domElement.clientWidth * 2 - 1, -(e.clientY / renderer.domElement.clientHeight * 2) + 1)

			let intersectsObjArr = getSelsectOBj(raycaster, e);//通过封装的getSelsectOBj函数获取鼠标选中对象集合，e是点击事件对象
			console.log(intersectsObjArr.point.y);
			if (intersectsObjArr) {
				// if (intersectsObjArr.object.name) {
				// 	generateShell();
				// }
				if (isShiftDown) {
					if (intersectsObjArr.object !== ground) {
						scene.remove(intersectsObjArr.object);
						objects.splice(objects.indexOf(intersectsObjArr.object), 1);
					}
					// create cube
				} else {
					const loader = new OBJLoader();
					new MTLLoader()
						.load('../../../src/obj/scar/male02.mtl', function (materials) {
							materials.preload();
							new OBJLoader()
								.setMaterials(materials)
								.load('../../../src/obj/scar/male02.obj', function (voxel) {
									voxel.position.copy(intersectsObjArr.point).add(intersectsObjArr.face.normal);
									voxel.position.divideScalar(50).floor().multiplyScalar(50).addScalar(25);
									scene.add(voxel);
									objects.push(voxel);
									scene.add(voxel);
								});
						});

					// const voxel = new THREE.Mesh(
					// 	new THREE.BoxGeometry(50, 50, 50),
					// 	new THREE.MeshBasicMaterial({ color: 0xff00 })
					// );
					// voxel.position.copy(intersectsObjArr.point).add(intersectsObjArr.face.normal);
					// voxel.position.divideScalar(50).floor().multiplyScalar(50).addScalar(25);
					// scene.add(voxel);
					// objects.push(voxel);
				}

				render();
			}
		}

		function onDocumentKeyDown(e) {
			switch (event.keyCode) {
				case 16: isShiftDown = true; break;
			}
		}

		function onDocumentKeyUp(e) {
			switch (event.keyCode) {
				case 16: isShiftDown = false; break;
			}
		}

		function onWindowResize() {
			SCREEN_WIDTH = window.innerWidth;
			SCREEN_HEIGHT = window.innerHeight;
			renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
			camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
			camera.updateProjectionMatrix();
		}

		var x = 1;
		function animate() {
			// x += 5;
			requestAnimationFrame(animate);
			render();
		}

		function render() {
			const delta = clock.getDelta();
			for (let i = 0; i < nCharacters; i++) {
				characters[i].update(delta);
			}
			renderer.render(scene, camera);
		}

		function generateShell() {
			const x = new THREE.Mesh(new THREE.BoxGeometry(50, 50, 50), new THREE.MeshBasicMaterial({ color: 0xffffff }));
			x.position.z = 200;
			console.log(x);
			scene.add(x);
		}
		// window.addEventListener('mousemove', mouseMoveFuc);
		//获取事件操作对象
		function getSelsectOBj(raycaster, e) {
			//将html坐标系转化为webgl坐标系，并确定鼠标点击位置
			raycaster.setFromCamera(pointer, camera);//以camera为z坐标，确定所点击物体的3D空间位置
			let intersects = raycaster.intersectObjects(objects, true);//确定所点击位置上的物体数量集合
			return intersects[0];//返回连线经过的第一个模型，既鼠标点击的模型
		}
	</script>

</body>

</html>